package com.retail.member.client.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.core.entity.result.Result;
import com.retail.core.util.WechatUtil;
import com.retail.member.client.UserClient;
import com.retail.member.entity.request.MemberUserRequest;
import com.retail.member.entity.vo.MemberUserVo;
import com.retail.member.entity.vo.RetailMultiTeamResVo;
import com.retail.member.entity.vo.RetailTeamResVo;
import com.retail.member.service.MemberUserService;
import com.retail.order.entity.vo.RetailSettleOrderVo;
import com.retail.order.entity.vo.SysAdminVerifyStasticResVo;
import com.retail.order.service.RetailSettleOrderService;
import com.retail.order.service.SysAdminVerifyService;
import com.retail.proxy.entity.request.SysAdminApplyProxyRequest;
import com.retail.proxy.entity.vo.ProxyMechanismCategoryVo;
import com.retail.proxy.entity.vo.SysAdminApplyProxyVo;
import com.retail.proxy.service.ProxyMechanismCategoryService;
import com.retail.proxy.service.SysAdminApplyProxyService;
import com.retail.shop.entity.vo.RetailShopVo;
import com.retail.shop.service.RetailShopService;
import com.retail.system.entity.request.AdminRequest;
import com.retail.system.entity.vo.AdminIncomePersonVo;
import com.retail.system.entity.vo.AdminStatisticsPersonVo;
import com.retail.system.entity.vo.AdminStatisticsShopVo;
import com.retail.system.entity.vo.AdminVo;
import com.retail.system.enums.AuditStatusEnums;
import com.retail.system.enums.UserTypeEnums;
import com.retail.system.service.AdminService;
import com.retail.system.service.FileService;
import com.retail.team.entity.request.RetailTeamAddSpRequest;
import com.retail.team.entity.vo.RetailTeamAddSpVo;
import com.retail.team.enums.VerifyFlagEnums;
import com.retail.team.service.RetailTeamAddSpService;
import com.retail.wxchat.entity.vo.WxchatMiniappConfigVo;
import com.retail.wxchat.service.WxchatMiniappConfigService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Service("userClient")
public class UserClientImpl implements UserClient {

    private final MemberUserService memberUserService;

    private final RetailShopService retailShopService;

    private final RetailSettleOrderService retailSettleOrderService;

    private final WxchatMiniappConfigService wxchatMiniappConfigService;

    private final FileService fileService;

    private final AdminService adminService;

    private final RetailTeamAddSpService retailTeamAddSpService;

    private final SysAdminVerifyService sysAdminVerifyService;

    public UserClientImpl(MemberUserService memberUserService, RetailShopService retailShopService, RetailSettleOrderService retailSettleOrderService, WxchatMiniappConfigService wxchatMiniappConfigService, FileService fileService, AdminService adminService, RetailTeamAddSpService retailTeamAddSpService, SysAdminVerifyService sysAdminVerifyService, ProxyMechanismCategoryService proxyMechanismCategoryService, SysAdminApplyProxyService sysAdminApplyProxyService) {
        this.memberUserService = memberUserService;
        this.retailShopService = retailShopService;
        this.retailSettleOrderService = retailSettleOrderService;
        this.wxchatMiniappConfigService = wxchatMiniappConfigService;
        this.fileService = fileService;
        this.adminService = adminService;
        this.retailTeamAddSpService = retailTeamAddSpService;
        this.sysAdminVerifyService = sysAdminVerifyService;
        this.proxyMechanismCategoryService = proxyMechanismCategoryService;
        this.sysAdminApplyProxyService = sysAdminApplyProxyService;
    }

    @Override
    public Result<Map<String, Object>> getWeixinOpenid(String jsCode) {
        WxchatMiniappConfigVo wxchatMiniappConfigVo = wxchatMiniappConfigService.getModelLimit1();
        Map<String, Object> wopid = WechatUtil.getOpenId(jsCode, wxchatMiniappConfigVo.getAppId(), wxchatMiniappConfigVo.getAppSecret());
        if (ObjectUtil.isEmpty(wopid) || wopid.size() == 0) {
            return Result.fail("没有获得openId信息");
        }
        return Result.success(wopid);
    }

    @Override
    public Result<AdminVo> getUserStatistics(String openid) {
        // 得到用户信息
        AdminVo adminVo = adminService.getUseByOpenId(openid);
        if (ObjectUtil.isNotEmpty(adminVo)) {

            // 商户统计
            if (ObjectUtil.equal(adminVo.getUserType(), UserTypeEnums.SHOP_TYPE.getValue())) {
                AdminStatisticsShopVo shopStaticsVo = retailSettleOrderService.statisticsOrder(adminVo.getId());
                adminVo.setAdminStatisticsShopVo(shopStaticsVo);
            } else {
                adminVo.setAdminStatisticsShopVo(new AdminStatisticsShopVo());
            }

            // 团队长统计
            if (ObjectUtil.equal(adminVo.getUserType(), UserTypeEnums.BUSINESS_TYPE.getValue())) {
                AdminStatisticsPersonVo personVo = adminService.statisticsPerson(adminVo.getId());
                adminVo.setAdminStatisticsPersonVo(personVo);
            } else {
                adminVo.setAdminStatisticsPersonVo(new AdminStatisticsPersonVo());
            }

            // 收益详情
            AdminIncomePersonVo adminIncomePersonVo = sysAdminVerifyService.statisticsIncomePerson(adminVo.getId());

            adminVo.setAdminIncomePersonVo(adminIncomePersonVo);
        }
        return Result.success(adminVo);
    }

    private final ProxyMechanismCategoryService proxyMechanismCategoryService;

    @Override
    public Result<AdminVo> getUser(String openid) {
        // 得到用户信息
        AdminVo adminVo = adminService.getUseByOpenId(openid);
        if (ObjectUtil.isNotEmpty(adminVo)) {
            if (ObjectUtil.isNotEmpty(adminVo.getAdminLevel())) {
                ProxyMechanismCategoryVo proxyMechanismVo = proxyMechanismCategoryService.getModel(adminVo.getAdminLevel());
                if (ObjectUtil.isNotEmpty(proxyMechanismVo)) {
                    adminVo.setAdminLevelName(proxyMechanismVo.getCategoryName());
                }
            }
            if (ObjectUtil.equal(adminVo.getUserType(), UserTypeEnums.SHOP_TYPE.getValue())) {
                RetailShopVo shopVo = retailShopService.getOwnerShopByOwnerId(adminVo.getId());
                if (ObjectUtil.isEmpty(shopVo)) {
                    shopVo = new RetailShopVo();
                }
                if (ObjectUtil.isNotEmpty(shopVo.getSanitaryLicensePhoto())) {
                    shopVo.setSanitaryLicensePhotos(Arrays.stream(shopVo.getSanitaryLicensePhoto().split(",")).collect(Collectors.toList()));
                }

                if (ObjectUtil.isNotEmpty(shopVo.getBusinessLicensePhoto())) {
                    shopVo.setBusinessLicensePhotos(Arrays.stream(shopVo.getBusinessLicensePhoto().split(",")).collect(Collectors.toList()));
                }

                if (ObjectUtil.isNotEmpty(shopVo.getCorporationPhoto())) {
                    shopVo.setCorporationPhotos(Arrays.stream(shopVo.getCorporationPhoto().split(",")).collect(Collectors.toList()));
                }

                if (ObjectUtil.isNotEmpty(shopVo.getDoorPhoto())) {
                    shopVo.setDoorPhotos(Arrays.stream(shopVo.getDoorPhoto().split(",")).collect(Collectors.toList()));
                }

                if (ObjectUtil.isNotEmpty(shopVo.getEvnPhoto())) {
                    shopVo.setEvnPhotos(Arrays.stream(shopVo.getEvnPhoto().split(",")).collect(Collectors.toList()));
                }

                if (ObjectUtil.isNotEmpty(shopVo.getDouyinPhoto())) {
                    shopVo.setDouyinPhotos(Arrays.stream(shopVo.getDouyinPhoto().split(",")).collect(Collectors.toList()));
                }
                adminVo.setOwnerShop(shopVo);
            } else {
                adminVo.setOwnerShop(new RetailShopVo());
            }
        }
        return Result.success(adminVo);
    }

    @Override
    public Result saveUser(MemberUserRequest userRequest) {
        MemberUserVo userVo = memberUserService.getModelByOpenId(userRequest.getOpenId());
        if (ObjectUtil.isEmpty(userVo)) {
            Long saveCount = memberUserService.save(userRequest);
            return Result.success(saveCount);
        } else {
            return Result.success(userVo.getId());
        }
    }

    @Override
    public Result uploadImage(MultipartFile file) {

        if (file == null || file.getSize() == 0) {
            return Result.fail("请上传文件");
        }
        return fileService.uploadFile(new MultipartFile[]{file});
    }

    /**
     * 用户注册
     *
     * @param adminRequest
     * @return
     */
    @Override
    public Result registerUser(AdminRequest adminRequest) {
        return adminService.registerUser(adminRequest);
    }

    /**
     * 更新用户信息
     *
     * @param adminRequest
     * @return
     */
    @Override
    public Result updateUserInfo(AdminRequest adminRequest) {
        return adminService.updateUserInfo(adminRequest);
    }

    @Override
    public Result<SysAdminVerifyStasticResVo> userstastics(Long adminId) {
        if (ObjectUtil.isEmpty(adminId) || ObjectUtil.equal(adminId, 0L)) {
            SysAdminVerifyStasticResVo res = SysAdminVerifyStasticResVo.builder().build();
            return Result.success(res);
        }

        AdminVo adminVo = adminService.getModel(adminId);
        if (ObjectUtil.isEmpty(adminVo)) {
            return Result.fail("查询失败！");
        }

        SysAdminVerifyStasticResVo res = sysAdminVerifyService.passVerifyStasticById(adminId);
        if (ObjectUtil.isEmpty(res)) {
            res = SysAdminVerifyStasticResVo.builder().build();
        }

        res.setAdminId(adminVo.getId());
        res.setAdminName(adminVo.getName());
        res.setAdmin(adminVo);

        return Result.success(res);
    }

    // 团队详情
    @Override
    public Result<RetailTeamResVo> teamDetail(Long adminId) {
        RetailTeamResVo retailTeamResVo = new RetailTeamResVo();
        teamDetailAdminInfo(adminId, retailTeamResVo);
        teamDetailShopInfo(adminId, retailTeamResVo);
        teamDetailOrderInfo(adminId, retailTeamResVo);
        return Result.success(retailTeamResVo);
    }

    private void teamDetailOrderInfo(Long adminId, RetailTeamResVo retailTeamResVo) {
        List<RetailSettleOrderVo> orderVos = retailSettleOrderService.findOwnerOrderByAdminId(adminId + "");
        retailTeamResVo.setOrders(orderVos);
    }

    private void teamDetailShopInfo(Long adminId, RetailTeamResVo retailTeamResVo) {
        // 用户信息
        List<RetailShopVo> myshops = retailShopService.findOwnerShopByAdminId(adminId + "");
        retailTeamResVo.setShops(myshops);
    }

    private void teamDetailAdminInfo(Long adminId, RetailTeamResVo retailTeamResVo) {
        AdminVo adminVo = adminService.getModel(adminId);
        retailTeamResVo.setAdmin(adminVo);
    }

    @Override
    public Result<RetailMultiTeamResVo> teams(Long adminId) {
        RetailMultiTeamResVo retailAdminResVo = new RetailMultiTeamResVo();
        List<AdminVo> allUser = new ArrayList<>();
        List<AdminVo> level1 = new ArrayList<>();
        List<AdminVo> level2 = new ArrayList<>();
        List<AdminVo> level3 = new ArrayList<>();
        AdminVo adminVo = adminService.getModel(adminId);
        adminVo.setAuditStatusName(AuditStatusEnums.getStatusValues(adminVo.getAuditStatus()));
        level1.add(adminVo);
        allUser.addAll(level1);
        retailAdminResVo.setLevel1User(level1);
        List<AdminVo> levelAdmin2 = adminService.childAdminByParentId(adminVo.getId());
        levelAdmin2.forEach(r -> {
            r.setAuditStatusName(AuditStatusEnums.getStatusValues(r.getAuditStatus()));
        });

        level2.addAll(levelAdmin2);
        allUser.addAll(level2);
        retailAdminResVo.setLevel2User(levelAdmin2);

        levelAdmin2.stream().forEach(admin -> {
            List<AdminVo> levelAdmin3 = adminService.childAdminByParentId(admin.getId());
            levelAdmin3.forEach(l3 -> {
                l3.setAuditStatusName(AuditStatusEnums.getStatusValues(l3.getAuditStatus()));
            });
            level3.addAll(levelAdmin3);
        });
        retailAdminResVo.setLevel3User(level3);
        allUser.addAll(level3);
        retailAdminResVo.setAllUser(allUser);

        return Result.success(retailAdminResVo);

    }

    @Override
    public Result<List<AdminVo>> myteams(Long adminId) {
        List<AdminVo> allUser = adminService.myteams(adminId);
        for (AdminVo adminVo : allUser) {
            adminVo.setAuditStatusName(AuditStatusEnums.getStatusValues(adminVo.getAuditStatus()));
        }
        return Result.success(allUser);
    }

    /**
     * 用户认证
     *
     * @param adminId
     * @param jsonObject
     * @return
     */
    @Override
    public Result<RetailTeamResVo> authInfo(Long adminId, JSONObject jsonObject) {
        String urlZm = MapUtil.getStr(jsonObject, "urlZm");
        String urlFm = MapUtil.getStr(jsonObject, "urlFm");
        if (urlZm == null || "".equals(urlZm)) {
            return Result.fail("请上传身份证正面！");
        }
        if (urlFm == null || "".equals(urlFm)) {
            return Result.fail("请上传身份证反面！");
        }
        adminService.authInfo(urlZm, urlFm, adminId);
        return Result.success();
    }

    @Override
    public Result<List<AdminVo>> noParentIdAdmin() {
        return Result.success(adminService.noParentIdAdmin());
    }

    @Override
    public Result<Integer> saveTeamAddSp(RetailTeamAddSpRequest request) {
        RetailTeamAddSpVo team = adminService.findTeamSpLimit1(request.getAdminId());
        if (ObjectUtil.isNotEmpty(team)) {
            return Result.fail("该区域合伙人绑定团队正在审核中，请稍后再试");
        }

        request.setVerifyTime(new Date());
        request.setVerifyFlag(0);
        request.setStatusFlag(StatusFlagEnum.USE.getValue());
        request.setDelFlag(DelFlagEnum.NO.getValue());
        request.setCreateUser(1L);
        request.setRemark("");
        Long count = retailTeamAddSpService.save(request);
        return Result.success(count);
    }


    private final SysAdminApplyProxyService sysAdminApplyProxyService;

    @Override
    public Result<Integer> applyPorxy(SysAdminApplyProxyRequest request) {
        SysAdminApplyProxyVo exitApplyProxy = sysAdminApplyProxyService.getModelByAdminIdAndVerifyFlag(request.getAdminId(), VerifyFlagEnums.DAI_SHEN_HE.getValue());
        if (ObjectUtil.isNotEmpty(exitApplyProxy)) {
            return Result.success("您提交的申请正在审核中，请勿重复申请");
        }

        request.setPayFlag(DelFlagEnum.NO.getValue());
        AdminVo adminVo = adminService.getModel(request.getAdminId());
        if (ObjectUtil.isNotEmpty(adminVo) && ObjectUtil.isNotEmpty(adminVo.getAdminLevel())) {
            request.setProxyOraCategoryId(adminVo.getAdminLevel());
        }

        request.setVerifyFlag(VerifyFlagEnums.DAI_SHEN_HE.getValue());
        request.setStatusFlag(StatusFlagEnum.USE.getValue());
        request.setDelFlag(DelFlagEnum.NO.getValue());
        sysAdminApplyProxyService.save(request);
        return Result.success("申请代理请求已提交，稍后会有客户联系您", request.getId());
    }

    @Override
    public Result updateCity(Long id, String city) {
        Integer updateCityCount = adminService.updateCity(id, city);
        return Result.success(updateCityCount);
    }
}
